package com.ruoyi.config

import com.tencentcloudapi.aiart.v20221229.AiartClient
import com.tencentcloudapi.common.Credential
import com.tencentcloudapi.common.profile.ClientProfile
import com.tencentcloudapi.common.profile.HttpProfile
import okhttp3.*
import org.json.JSONObject
import org.springframework.boot.context.properties.ConfigurationProperties


@ConfigurationProperties(prefix = "ai.tencent")
class TencentApiProperties(

    var secretId: String? = null,
    var secretKey: String? = null,
    var region: String? = null
)


fun TencentApiProperties.client(): AiartClient =
    AiartClient(Credential(secretId, secretKey), "ap-guangzhou", ClientProfile().apply { httpProfile = HttpProfile().apply { endpoint = this@client.region } })


@ConfigurationProperties(prefix = "ai.baidu")
class BaiduApiProperties(

    var appKey: String? = null,
    var appSecret: String? = null
)

val HTTP_CLIENT: OkHttpClient = OkHttpClient().newBuilder().build()

fun BaiduApiProperties.token(): String {

    val mediaType = MediaType.parse("application/x-www-form-urlencoded")
    val body: RequestBody = RequestBody.create(
        mediaType, "grant_type=client_credentials&client_id=$appKey&client_secret=$appSecret"
    )
    val request: Request = Request.Builder()
        .url("https://aip.baidubce.com/oauth/2.0/token")
        .method("POST", body)
        .addHeader("Content-Type", "application/x-www-form-urlencoded")
        .build()
    val response: Response = HTTP_CLIENT.newCall(request).execute()
    return JSONObject(response.body()?.string()).getString("access_token")
}